package cn.lirenyi.basic.util;

import cn.lirenyi.user.domain.Logininfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * 登录上下文
 *  1.登录人的信息
 *  2.当前登录人的权限
 */
public class LoginContext {

    public static Logininfo currentLoginInfo(HttpServletRequest request){
        String token = request.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            // 获得Spring容器
            WebApplicationContext applicationContext =
                    WebApplicationContextUtils.getWebApplicationContext(request.getServletContext());
            // 通过Spring容器获取想要的对象
            RedisTemplate redisTemplate = (RedisTemplate) applicationContext.getBean("redisTemplate");
            Object loginInfoTmp = redisTemplate.opsForValue().get(token);
            if(loginInfoTmp != null){
                return (Logininfo) loginInfoTmp;
            }
        }
        return null;
    }
}
